package com.hnas.sys.web.basic;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hnas.core.dto.BaseAjaxResponse;
import com.hnas.sys.core.util.CacheUtil;
import com.hnas.sys.core.util.UserUtils;
import com.hnas.sys.dao.ResourceDAO;
import com.hnas.sys.service.system.AuthorityService;
import com.hnas.sys.service.system.MenuPackageService;
import com.hnas.sys.service.system.ResourceService;
import com.hnas.sys.service.system.UserService;
import com.hnas.sys.service.system.dto.DTOUser;
@Controller
@RequestMapping("/backend/user")
public class UserControl {
	@Autowired
	UserService userService;
	@Autowired
	private UserCache userCache;
	@Autowired
	ResourceService resourceService;
	@Autowired
	MenuPackageService menuPackageService;
	@Autowired
	AuthorityService authorityService;
	@Autowired
	ResourceDAO resourceDAO;
	@RequestMapping("/updateme")
	@ResponseBody
	public BaseAjaxResponse update(@ModelAttribute("updateAllCache")String updateAllCache	,HttpServletRequest request) {
		BaseAjaxResponse response = new BaseAjaxResponse();
		try {			
			if(null != updateAllCache && updateAllCache.equalsIgnoreCase("true") ) {
				//更新所有缓存
				CacheUtil.setAuthorityCache(authorityService.loadAll());
				CacheUtil.setMenuPackageCache(menuPackageService.loadAll());
				CacheUtil.setResourceCache(resourceService.loadAllResource());
				CacheUtil.setMetaDataCache(resourceDAO.loadAllReference());
			}
			DTOUser user = userService.getUserById(UserUtils.getCurrentUser().getId());
			userCache.putUserInCache(user);
			 request.getSession().setAttribute("backend_menus", 
		        		this.resourceService.getUserMenus(user));
			response.setResult(BaseAjaxResponse.SUCCESS);
		} catch (Exception e) {
			response.setErrorMessage(e.getMessage());
		}
		
		return response;
	}
}
